package cn.zxcoder.controller.SystemManage.role;

import cn.zxcoder.Tools.ToolUtil;
import cn.zxcoder.entity.Res;
import cn.zxcoder.entity.RoleRight;
import cn.zxcoder.entity.SystemManage.Right;
import cn.zxcoder.entity.SystemManage.Role;
import cn.zxcoder.service.IRightService;
import cn.zxcoder.service.IRoleRightService;
import cn.zxcoder.service.IRoleService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zx
 * @since 2023-05-12
 */
@RestController
@Api(tags = "用于做权限管理的前端控制器")
@RequestMapping("/api/Role")
public class RoleController {


    @Autowired
    IRightService iRightServiceIml;

    @Autowired
    IRoleService iRoleServiceIml;

    @Autowired
    IRoleRightService iRoleRightServiceIml;
    @ApiOperation(value = "角色管理-获取角色列表")
    @PostMapping("/list")
    @Transactional(readOnly = true)
    public Res getRight(@RequestParam String page, @RequestParam String limit, @RequestParam String roleName,
                        @RequestParam String roleCode) {

        Page<Role> rolePage = new Page<>(Integer.parseInt(page), Integer.parseInt(limit));
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        if (!roleName.equals("")) {
            roleQueryWrapper.like("role_name", roleName);
        }
        if (!roleCode.equals("")) {
            roleQueryWrapper.like("role_code", roleCode);
        }
        Page<Role> page1 = iRoleServiceIml.page(rolePage, roleQueryWrapper);
        return new Res(true, JSON.toJSONString(page1), "获取角色列表成功");

    }


    @ApiOperation(value = "角色管理-保存（添加编辑）")
    @PostMapping("/save")
    @Transactional

    public Res saveRight(@RequestParam String roleId, @RequestParam String roleName, @RequestParam String roleCode,
                         @RequestParam String sysCode, @RequestParam String token,@RequestParam boolean issave) {

        Role role = new Role();
        role.setRoleName(roleName);
        role.setRoleCode(roleCode);
        role.setSysCode(sysCode);
        role.setEditTime(new Date());
        role.setEditUser(token);
        if (issave) {

            //这里还要设置基础的权限字符串(roleRights)
            String rights = "1,6,24,25,5,23";
            role.setRoleRights(rights);


            boolean save = iRoleServiceIml.save(role);

            //添加角色权限表
            RoleRight roleRight = new RoleRight();
            roleRight.setroleId(role.getId());
            iRoleRightServiceIml.save(roleRight);

            return new Res(save, null, save ? "此角色信息保存成功" : "此角色信息保存失败");
        } else {
            UpdateWrapper<Role> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", Integer.parseInt(roleId));
            boolean update = iRoleServiceIml.update(role, wrapper);
            return new Res(update, null, update ? "此角色信息编辑成功" : "此角色信息编辑失败");
        }
    }

    @ApiOperation(value = "角色管理-删除角色")
    @DeleteMapping("/delete/{id}")
    @Transactional

    public Res saveRight(@PathVariable String id) {

        boolean b = iRoleServiceIml.removeById(Integer.parseInt(id));
            return new Res(b, null, b ? "删除角色成功" : "删除角色失败");

    }



    @ApiOperation(value = "通过一个role数据获取菜单权限")
    @GetMapping("/tree/{id}")
    @Transactional

    public Res getTreeRight(@PathVariable String id) {
        //找到指定的role
//        Role role = iRoleServiceIml.getById(Integer.parseInt(id));(一对多)
//        //查询此角色role的权限字符串
//        String roleRights = role.getRoleRights();
        QueryWrapper<RoleRight> roleRightQueryWrapper = new QueryWrapper<>();
        roleRightQueryWrapper.eq("role_id", Integer.parseInt(id));
        String roleRights = iRoleRightServiceIml.getOne(roleRightQueryWrapper).getRightsIds();

        //转换为权限id数组
        String[] strings = roleRights.split(",");
        List<Integer> ids = Arrays.stream(strings).map(Integer::parseInt).collect(Collectors.toList());

        //设置它的children数组属性
        List<Right> res = ToolUtil.setchildren(ids, iRightServiceIml);

        return new Res(true, JSON.toJSONString(res), "成功获取菜单权限");

    }

    @ApiOperation(value = "保存菜单权限")
    @PostMapping("/tsave")
    @Transactional

    public Res getTreeRight(@RequestParam String roleId, @RequestParam String rightIds) {
        //找到相应的权限字符串
        Role role = iRoleServiceIml.getById(Integer.parseInt(roleId));
        String rights = role.getRoleRights();

        //增加权限到字符串中
        UpdateWrapper<Role> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", Integer.parseInt(roleId));
        wrapper.set("role_rights", rights+","+rightIds);
        boolean update = iRoleServiceIml.update(wrapper);
        return new Res(update, null, update ? "设置权限成功" : "设置权限失败");

    }




}
